import { createAsyncThunk } from '@reduxjs/toolkit';
import { IUserInfo } from 'src/interface';
import { setToken } from 'src/utils/storage';
import { login as reqLogin, getUserInfo as reqGetUserInfo } from 'src/api/modules/user';
import { RootState } from 'src/store';
import { setMenus } from 'src/store/action';

// 登录
export const login = createAsyncThunk<string, Required<Pick<IUserInfo, 'username' | 'password'>>>(
  'user/login',
  async (data, { rejectWithValue }) => {
    try {
      const result = await reqLogin(data);
      if (!result) {
        return rejectWithValue('');
      }
      setToken(result);
      return result;
    } catch (err) {
      return rejectWithValue(err);
    }
  },
);

// 获取用户信息
export const getUserInfo = createAsyncThunk<IUserInfo | null>(
  'user/getUserInfo',
  async (_, { getState, rejectWithValue, dispatch }) => {
    const { user } = getState() as RootState;
    if (!user.token) {
      return null;
    }
    try {
      const result = await reqGetUserInfo();
      const { sysUser, menus } = result;
      dispatch(setMenus(menus));
      return sysUser;
    } catch (err) {
      return rejectWithValue(err);
    }
  },
);
